package com.yt.controller;

import com.yt.dao.AccountDao;
import com.yt.entity.Account;
import com.yt.util.CommonResult;
import io.seata.core.context.RootContext;
import io.seata.integration.http.XidResource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * @Classname AccountController
 * @Description
 * @Date 2021/11/2 15:55
 * @Create by 杨涛
 */
@RestController
@Slf4j
@RefreshScope
public class AccountController {

    @Resource
    AccountDao accountDao;

    @RequestMapping("/account/decrease")
    public CommonResult decrease(@RequestParam("userId") Long userId
            , @RequestParam("money") BigDecimal money,@RequestParam("xid") String xid) {
        RootContext.bind(xid);
        Account account = accountDao.getAccountByuserId(userId);
        if (account.getResidue().subtract(money).floatValue() >= 0) {
            account.setResidue(account.getResidue().subtract(money));
            account.setUsed(account.getUsed().add(money));
            accountDao.updateAccount(account);
            XidResource.cleanXid(xid);
            return new CommonResult(200, "支付成功");
        } else {
            throw new RuntimeException("余额不足") ;
        }
    }
}
